package com.whilelife.Wachovia.ui;

import com.whilelife.Wachovia.parser.StatementReader;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Brent Merle
 * Date: Nov 3, 2011
 * Time: 4:54:16 PM
 */
public class MainDisplay extends JPanel implements ActionListener {

  private final JFileChooser jfc = new JFileChooser();
  private final JButton btnChooseDir = new JButton("...");
  private final JButton btnDoParse = new JButton("Parse Files");
  private final JButton btnSaveCSV = new JButton("Save data as CSV");
  private final JButton btnClear = new JButton("Reset Data");
  private final JTextField jtfDirectory = new JTextField(jfc.getCurrentDirectory().getAbsolutePath());
  private final SpringLayout sl = new SpringLayout();
  private final DefaultListModel listModel = new DefaultListModel();
  private final JList listFiles = new JList(listModel);

  public MainDisplay() {
    super();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    setLayout(sl);
    buildUI();
  }

  private void buildUI() {
    btnChooseDir.setToolTipText("Choose the directory where your PDF statements are located");

    this.add(jtfDirectory);
    this.add(btnChooseDir);
    JScrollPane jsp = new JScrollPane(listFiles);
    this.add(jsp);
    this.add(btnDoParse);
    this.add(btnSaveCSV);
    this.add(btnClear);



    sl.putConstraint(SpringLayout.WEST, jtfDirectory, 10, SpringLayout.WEST, this);
    sl.putConstraint(SpringLayout.EAST, jtfDirectory, -50, SpringLayout.EAST, this);
    sl.putConstraint(SpringLayout.NORTH, jtfDirectory, 10, SpringLayout.NORTH, this);

    sl.putConstraint(SpringLayout.WEST, btnChooseDir, 10, SpringLayout.EAST, jtfDirectory);
    sl.putConstraint(SpringLayout.EAST, btnChooseDir, -10, SpringLayout.EAST, this);
    sl.putConstraint(SpringLayout.NORTH, btnChooseDir, 10, SpringLayout.NORTH, this);
    sl.putConstraint(SpringLayout.SOUTH, btnChooseDir, 0, SpringLayout.SOUTH, jtfDirectory);

    sl.putConstraint(SpringLayout.WEST, btnDoParse, 10, SpringLayout.WEST, this);
    sl.putConstraint(SpringLayout.NORTH, btnDoParse, -30, SpringLayout.SOUTH, this);

    sl.putConstraint(SpringLayout.WEST, btnSaveCSV, 10, SpringLayout.EAST, btnDoParse);
    sl.putConstraint(SpringLayout.NORTH, btnSaveCSV, 0, SpringLayout.NORTH, btnDoParse);

    sl.putConstraint(SpringLayout.WEST, btnClear, 10, SpringLayout.EAST, btnSaveCSV);
    sl.putConstraint(SpringLayout.NORTH, btnClear, 0, SpringLayout.NORTH, btnSaveCSV);

    sl.putConstraint(SpringLayout.WEST, jsp, 10, SpringLayout.WEST, this);
    sl.putConstraint(SpringLayout.EAST, jsp, -10, SpringLayout.EAST, this);
    sl.putConstraint(SpringLayout.NORTH, jsp, 10, SpringLayout.SOUTH, jtfDirectory);
    sl.putConstraint(SpringLayout.SOUTH, jsp, -10, SpringLayout.NORTH, btnDoParse);

    setListeners();

  }

  private void setListeners() {
    btnChooseDir.addActionListener(this);
    btnDoParse.addActionListener(this);
    btnSaveCSV.addActionListener(this);
    btnClear.addActionListener(this);
  }

  public static void main(String[] args) {

    JFrame jf = new JFrame();
    jf.setSize(600, 400);
    jf.setContentPane(new MainDisplay());
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setVisible(true);
    jf.setTitle("Wachovia/Wells Fargo Statement Converter");

  }

  /*public static void main(String[] args) {
    if (args.length < 1) {
      System.err.println("Need to include a file path to read");
      System.exit(1);
    }
    List<String> files = Arrays.asList(args);
    FileReader fr = new FileReader(files);
    try {
      fr.doIt();
    } catch (IOException e) {
      e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

  }*/

  private void getFilesInDirectory(File dir) {
    if (!dir.isDirectory()) {
      return;
    }

    String[] children = dir.list(new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith("pdf");
      }
    });

    listModel.removeAllElements();
    for (String str : children) {
      listModel.addElement(str);
    }

  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(btnChooseDir)) {
      if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        jtfDirectory.setText(jfc.getSelectedFile().getAbsolutePath());
        getFilesInDirectory(jfc.getSelectedFile());
      }
    } else if (e.getSource().equals(btnDoParse)) {
      if (listFiles.getSelectedValues().length == 0) {
        listFiles.setSelectionInterval(0, listModel.getSize() - 1);
      }
      ArrayList<String> fullFiles = new ArrayList<String>();
      for (Object obj : listFiles.getSelectedValues()) {
        fullFiles.add(jtfDirectory.getText() + "\\" + obj);
      }
      try {
        StatementReader.parseStatements(fullFiles);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    } else if (e.getSource().equals(btnSaveCSV)) {
      JFileChooser jfw = new JFileChooser(jfc.getSelectedFile());
      if (jfw.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
          BufferedWriter bw = new BufferedWriter(new FileWriter(jfw.getSelectedFile()));
          bw.write(StatementReader.getCSVForAllAccounts());
          bw.flush();
          bw.close();
          JOptionPane.showMessageDialog(this, "Data saved to: " + jfw.getSelectedFile().getAbsolutePath(), "Success", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e1) {
          e1.printStackTrace();
          JOptionPane.showMessageDialog(this, "Failed to save the file: " + e1.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
        }
      }
    } else if (e.getSource().equals(btnClear)) {
      StatementReader.reset();
    }
  }
}
